<?php

namespace Cck\ArticlesSystem\Http\Models;

use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Builder;
use Illuminate\Database\Eloquent\Collection;
use Illuminate\Database\Eloquent\SoftDeletes;
use Cck\ArticlesSystem\Http\ModelObserves\CategoryObserve;

/**
 * 文章分类
 * @property string $name
 * @property string $slug
 * @property string $url_type
 * @property integer $parent_id
 * @property integer $order
 * @property string $seo_title
 * @property string $seo_keywords
 * @property string $seo_description
 * @property boolean $show_in_menus
 * @property boolean $page
 * @property string $page_html
 * 
 * @method Builder isPage()
 * @method Builder notPage()
 * @method Builder inMenu()
 * @method Builder notInMenu()
 * 
 * @property-read self $parent
 * @property-read self[]|Collection $children
 * @property-read Article[]|Collection $articles
 */
class Category extends Model
{
    use SoftDeletes;

    protected $table = 'categories';

    const URL_TYPE_ID = 'id';
    const URL_TYPE_ALIAS = 'alias';
    const URL_TYPE_LINK = 'link';

    protected $fillable = [
        'name', 'slug', 'url_type', 'parent_id', 'order', 'seo_title', 'seo_keywords', 'seo_description', 'show_in_menus', 'page', 'page_html'
    ];

    protected $dates = [
        'deleted_at'
    ];

    protected $casts = [
        'parent_id' => 'integer',
        'order' => 'integer',
        'show_in_menus' => 'boolean',
        'page' => 'boolean'
    ];

    protected static function boot()
    {
        parent::boot();

        static::observe(CategoryObserve::class);
    }

    public static function getUrlTypeOptions(): array
    {
        return [
            self::URL_TYPE_ID => 'ID',
            self::URL_TYPE_ALIAS => '别名',
            self::URL_TYPE_LINK => '链接'
        ];
    }

    public function getUrlAttribute()
    {
        return '';
    }

    public function articles()
    {
        return $this->hasMany(Article::class, 'category_id', 'id');
    }

    public function parent()
    {
        return $this->belongsTo(self::class, 'parent_id', 'id');
    }

    public function children()
    {
        return $this->hasMany(self::class, 'parent_id', 'id');
    }

    public function scopeIsPage($q)
    {
        return $q->where('page', true);
    }

    public function scopeNotPage($q)
    {
        return $q->where('page', false);
    }

    public function scopeInMenu($q)
    {
        return $q->where('show_in_menus', true);
    }

    public function scopeNotInMenu($q)
    {
        return $q->where('show_in_menus', false);
    }
}
